<template>
  <el-container>
    <!-- 侧边栏 -->
    <el-aside class="home-aside" width="250px">
      <!-- logo -->
      <div class="home-logo-div">
        <router-link to="/customer/home">
          <el-image
            class="home-logo"
            src="../src/assets/logo_trans.png"
            fit="contain"
          ></el-image
        ></router-link>
      </div>
      <!-- 折叠icon -->
      <el-icon
        class="toggle-button"
        v-model="isCollapse"
        @click="toggleCollapse"
        size="20px"
      >
        <Fold v-if="!isCollapse" />
        <Expand v-if="isCollapse" />
      </el-icon>
      <!-- 侧边栏菜单 -->
      <el-menu
        class="home-menu-vertical"
        :collapse="isCollapse"
        :default-active="$route.path"
        router
        active-text-color="#E3A566"
      >
        <el-menu-item index="/customer/food">
          <el-icon><Search /></el-icon>
          <span slot="title">菜品列表</span>
        </el-menu-item>
        <el-menu-item index="/customer/recommend">
          <el-icon><MagicStick /></el-icon>
          <span slot="title">猜你想吃</span>
        </el-menu-item>
        <el-menu-item index="/customer/order">
          <el-icon><Wallet /></el-icon>
          <span slot="title">我的订单</span>
        </el-menu-item>
        <el-menu-item index="/customer/account">
          <el-icon><User /></el-icon>
          <span slot="title">我的账号</span>
        </el-menu-item>
      </el-menu>
      <el-image src="../src/assets/plate.png" class="plate-div"></el-image>
    </el-aside>

    <el-container>
      <!-- 头部 -->
      <el-header class="food-header" height="40px">
        <div class="ball"></div>
        <div class="food-line"></div>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/customer/home' }"> 主页 </el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/customer/food' }"
            >菜品列表</el-breadcrumb-item
          >
          <el-breadcrumb-item>下单</el-breadcrumb-item>
        </el-breadcrumb>
      </el-header>

      <!-- 主体 -->
      <el-main class="home-main">
        <el-scrollbar height="590px">
          <el-card class="checkout-card">
            <div>确认订单</div>
            <el-radio-group v-model="dine" class="checkout-dine-button">
              <el-radio-button label="dinein">堂食</el-radio-button>
              <el-radio-button label="dineout">外卖</el-radio-button>
            </el-radio-group>
            <!-- 选择地址的按钮 -->
            <div v-if="dine === 'dineout'">
              <el-button class="checkout-dineout-button" plain @click="setAddress"
                ><div class="checkout-address">{{ chooseAddress.address }}</div>
                <br />
                <span>{{ chooseAddress.recipientName }}</span
                >&nbsp&nbsp&nbsp&nbsp&nbsp<span>{{ chooseAddress.phoneNumber }}</span>
                <div class="checkout-address-icon">
                  <el-icon><ArrowRightBold /></el-icon>
                </div>
              </el-button>
            </div>

            <!-- 菜品列表 -->
            <el-row :gutter="30">
              <el-col v-for="foodEntity in foodInCart" :key="foodEntity.id" :span="24">
                <!-- 左侧图像 -->
                <el-image class="food-cart-image" :src="foodEntity.photo" fit="cover">
                </el-image>
                <!-- 右侧信息 -->
                <div class="checkout-food-title">
                  <span style="font-size: 20px">{{ foodEntity.foodName }}</span
                  ><br />
                  <span>×&nbsp{{ foodEntity.foodNumber }}&nbsp</span>
                </div>
                <div class="checkout-food-price">
                  <span>￥ {{ calculateTotalPrice(foodEntity) }}</span>
                </div>
              </el-col>
            </el-row>
            <div>总价：￥ {{ calculateOrderPrice() }}</div>
            <!-- 操作订单按钮 -->
            <div class="checkout-operation">
              <el-button class="checkout-return" type="warning" text @click="gotoFood"
                ><el-icon size="30px"><Back /></el-icon>加菜
              </el-button>
              <el-button class="loginBtn" round color="#E3A566" @click="confirmOrder"
                >下单</el-button
              >
            </div>
          </el-card>
        </el-scrollbar>
      </el-main>
      <!-- 回到顶部 -->
      <el-backtop :right="80" :bottom="100" />
    </el-container>
  </el-container>
  <!-- 设置地址的抽屉 -->
  <el-drawer v-model="drawer" direction="rtl">
    <template #header>
      <h4>选择收货地址</h4>
    </template>
    <div class="checkout-address-div">
      <el-row :gutter="30" v-for="addressEntity in addressList" :key="addressEntity.id">
        <el-col :span="24" class="checkout-address-col">
          <el-radio
            class="checkout-address-radio"
            v-model="radio1"
            :label="addressEntity.id"
            size="large"
          >
            <div class="checkout-address">
              <el-tag
                type="info"
                size="small"
                v-if="addressEntity.isDefaultAddress === true"
                >默认</el-tag
              >&nbsp{{ addressEntity.address }}
            </div>
            <span>{{ addressEntity.recipientName }}</span
            >&nbsp&nbsp&nbsp&nbsp&nbsp<span>{{ addressEntity.phoneNumber }}</span>
          </el-radio>
          <el-button
            round
            type="warning"
            text
            @click="openEditDialog(addressEntity.id)"
            class="checkout-address-delete-btn"
          >
            <el-icon><Edit /></el-icon
          ></el-button>
          <el-button
            round
            type="warning"
            text
            @click="deleteAddress(addressEntity.id)"
            class="checkout-address-delete-btn"
          >
            <el-icon><Delete /></el-icon></el-button></el-col
      ></el-row>
    </div>
    <el-button class="checkout-address-add-button" @click="writeAddress"
      >新增收货地址</el-button
    >
    <template #footer>
      <div style="flex: auto">
        <el-button class="loginBtn" round color="#E3A566" @click="confirmAddress"
          >确认</el-button
        >
      </div>
    </template>
  </el-drawer>
  <!-- 填写配送地址 -->
  <el-dialog v-model="dialogFormVisible" title="设置配送地址">
    <el-form :model="addressForm" :rules="addressRules" ref="addressRuleForm">
      <el-form-item label="地址" prop="address">
        <el-input v-model="addressForm.address" autocomplete="off" />
      </el-form-item>
      <el-form-item label="收件人" prop="recipientName">
        <el-input v-model="addressForm.recipientName" autocomplete="off" />
      </el-form-item>
      <el-form-item label="电话号码" prop="phoneNumber">
        <el-input v-model="addressForm.phoneNumber" autocomplete="off" />
      </el-form-item>
      <el-form-item label="是否为默认地址" prop="isDefaultAddress">
        <el-radio-group v-model="addressForm.isDefaultAddress">
          <el-radio label="1">默认地址</el-radio>
          <el-radio label="0">非默认地址</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button class="loginBtn" round color="#E3A566" @click="addAddress"
          >确认</el-button
        >
      </span>
    </template>
  </el-dialog>
  <!-- 编辑配送地址 -->
  <el-dialog v-model="editDialogFormVisible" title="编辑配送地址">
    <el-form :model="editForm" :rules="addressRules" ref="addressRuleForm">
      <el-form-item label="地址" prop="address">
        <el-input v-model="editForm.address" autocomplete="off" />
      </el-form-item>
      <el-form-item label="收件人" prop="recipientName">
        <el-input v-model="editForm.recipientName" autocomplete="off" />
      </el-form-item>
      <el-form-item label="电话号码" prop="phoneNumber">
        <el-input v-model="editForm.phoneNumber" autocomplete="off" />
      </el-form-item>
      <el-form-item label="是否为默认地址" prop="isDefaultAddress">
        <el-radio-group v-model="editForm.isDefaultAddress">
          <el-radio label="1">默认地址</el-radio>
          <el-radio label="0">非默认地址</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button class="loginBtn" round color="#E3A566" @click="editAddress"
          >确认</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { mapState } from "vuex";
export default {
  data() {
    return {
      isCollapse: false, //是否折叠侧边栏
      dine: "dinein",
      dialogFormVisible: false,
      editDialogFormVisible: false, // 编辑地址对话框
      addressList: [
        // {
        //   id: 1,
        //   userID: 1,
        //   recipientName: "xxx",
        //   phone: 135564,
        //   address: "123123123",
        //   isDefault: true,
        // }
      ],
      addressRules: {
        address: [{ required: true, message: "请输入地址", trigger: "change" }],
        recipientName: [
          { required: true, message: "请输入收货人姓名", trigger: "change" },
        ],
        phoneNumber: [
          { required: true, message: "请输入手机号", trigger: "change" },
          { min: 11, max: 11, message: "请输入11位手机号", trigger: "blur" },
        ],
        isDefaultAddress: [
          { required: true, message: "请设置是否为默认地址", trigger: "change" },
        ],
      },
      FoodList: [],
      chooseAddress: {},
      drawer: false,
      radio1: 0, // 即address的id
      addressForm: {
        userID: "",
        address: "",
        recipientName: "",
        phoneNumber: "",
        isDefaultAddress: "0",
      },
      editForm: {
        userID: "",
        address: "",
        recipientName: "",
        phoneNumber: "",
        isDefaultAddress: "0",
      },
      account: {},
      order: {},
    };
  },
  computed: {
    ...mapState({
      foodInCart: (state) => state.foodInCart, // 注意路径是否正确
    }),
  },
  created() {
    this.account = JSON.parse(this.$store.state.account);
    let url = "/address/userID/" + this.account.id;
    let _this = this;
    this.$http.get(url).then(function (response) {
      //_this.foodList=response.data
      _this.addressList = response.data;
      console.log("_this.addressList = ", _this.addressList);
      //找到默认地址的位置
      const index = _this.addressList.findIndex((option) => option.isDefaultAddress);
      console.log(index);
      // 没有地址
      if (index === -1) {
        _this.chooseAddress = { address: "暂无默认地址  去设置" };
        return;
      }
      _this.radio1 = _this.addressList[index].id;
      //初始选择的address是默认地址
      _this.chooseAddress = _this.addressList[index];
      console.log(_this.radio1);
    });
  },
  methods: {
    // 切换侧边栏的折叠与展开
    toggleCollapse() {
      this.isCollapse = !this.isCollapse;
    },

    calculateTotalPrice(foodEntity) {
      // console.log(foodEntity,foodEntity.price,foodEntity.foodNumber)
      let price = (foodEntity.price * 10 * foodEntity.foodNumber) / 10; // 计算总价
      // console.log(price)
      return price;
    },
    calculateOrderPrice() {
      let _this = this;
      let totalPrice = 0;
      for (let i = 0; i < _this.foodInCart.length; i++) {
        totalPrice +=
          (_this.foodInCart[i].price * 10 * _this.foodInCart[i].foodNumber) / 10;
      }
      return totalPrice;
    },
    setAddress() {
      this.drawer = true;
    },
    confirmAddress() {
      const index = this.addressList.findIndex((option) => option.id === this.radio1);
      this.chooseAddress = this.addressList[index];
      this.drawer = false;
    },
    openEditDialog(id) {
      let _this = this;
      _this.editDialogFormVisible = true;
      const index = _this.addressList.findIndex((option) => option.id === id);
      _this.editForm = _this.addressList[index];
      if (_this.editForm.isDefaultAddress === true) {
        _this.editForm.isDefaultAddress = "1";
      } else {
        _this.editForm.isDefaultAddress = "0";
      }
    },
    editAddress() {
      var _this = this;
      let url = "/address";
      _this.editForm.userID = _this.account.id;
      console.log("_this.editForm = ", _this.editForm);
      _this.$refs["addressRuleForm"].validate((valid) => {
        //如果数据格式不符合要求,直接返回
        if (!valid) {
          _this.$message({
            message: "请输入正确格式的信息！",
            type: "error",
          });
          return;
        }
        // 取消之前的默认地址
        const index = _this.addressList.findIndex(
          (option) => option.isDefaultAddress === true
        );
        console.log("之前的默认地址index = ", index);
        console.log("之前的_this.addressList = ", _this.addressList);
        if (index !== -1) {
          _this.addressList[index].isDefaultAddress = false;
          console.log("删除之前的默认地址后_this.addressList = ", _this.addressList);
        }

        if (_this.editForm.isDefaultAddress === "0") {
          _this.editForm.isDefaultAddress = false;
        } else {
          _this.editForm.isDefaultAddress = true;
        }
        //数据格式符合要求，封装信息请求后端
        _this.$http.put(url, _this.editForm).then(function (response) {
          _this.$message({
            message: "编辑地址成功！",
            type: "success",
          });

          console.log("原_this.addressList = ", _this.addressList);
          // 更新_this.addressList的数据
          const index = _this.addressList.findIndex(
            (option) => option.id === response.data.id
          );
          _this.addressList[index] = _this.editForm;
          _this.editDialogFormVisible = false;
        });
      });
    },
    deleteAddress(id) {
      console.log(id);
      let url = "/address/" + id + "/" + this.account.id;
      let _this = this;
      _this.$messageBox.confirm("确定删除该地址").then(function (res) {
        _this.$http
          .delete(url)
          .then(function (res) {
            _this.$message({
              message: "成功删除地址！",
              type: "success",
            });
            const index = _this.addressList.findIndex((option) => option.id === id);
            _this.addressList.splice(index, 1);
            console.log("删除地址后的_this.addressList = ", _this.addressList);
            if (_this.radio1 === id) {
              console.log("重新设置默认地址");
              _this.chooseAddress = _this.addressList[0];
              _this.radio1 = _this.chooseAddress.id;
            }
          })
          .catch((e) => this.$message.error(e.response.data));
      });
    },
    writeAddress() {
      this.dialogFormVisible = true;
    },
    addAddress() {
      var _this = this;
      let url = "/address";
      _this.addressForm.userID = _this.account.id;
      console.log("addAddress: _this.addressForm = ", _this.addressForm);
      _this.$refs["addressRuleForm"].validate((valid) => {
        //如果数据格式不符合要求,直接返回
        if (!valid) {
          _this.$message({
            message: "请输入正确格式的信息！",
            type: "error",
          });
          return;
        }
        // 取消之前的默认地址
        const index = _this.addressList.findIndex(
          (option) => option.isDefaultAddress === true
        );
        if (index !== -1) {
          _this.addressList[index].isDefaultAddress = false;
        }
        // 处理默认地址字段类型
        if (_this.addressForm.isDefaultAddress === "0") {
          _this.addressForm.isDefaultAddress = false;
        } else {
          _this.addressForm.isDefaultAddress = true;
        }
        //数据格式符合要求，封装信息请求后端
        _this.$http.post(url, _this.addressForm).then(function (response) {
          _this.$message({
            message: "设置地址成功！",
            type: "success",
          });
          _this.addressList.push(response.data);
          console.log("addAddress: _this.addressList = ", _this.addressList);
          _this.chooseAddress = response.data;
          _this.dialogFormVisible = false;
        });
      });
    },
    gotoFood() {
      let _this = this;
      console.log(this.$store.state.foodInCart);
      _this.$router.push({
        path: "/customer/food",
      });
    },
    // 下单
    confirmOrder() {
      let _this = this;
      console.log(this.foodInCart[0].id);
      this.order.userID = this.account.id;
      this.order.addressID = this.chooseAddress.id;
      let price = 0;
      //堂食的地址默认为0
      if (this.dine == "dinein") this.order.addressID = 0;
      //计算订单的总价格
      for (let i = 0; i < this.foodInCart.length; i++) {
        this.foodInCart[i].userID = this.account.id;
        console.log(this.foodInCart[i].foodID);
        price += this.foodInCart[i].price * this.foodInCart[i].foodNumber;
      }
      this.order.price = price;
      this.order.foodJudgementList = this.foodInCart;
      this.order.orderTime = new Date().valueOf();
      let url = "orders";
      this.$http.post(url, this.order).then(function (response) {
        //_this.foodList=response.data
        _this.$message({
          message: "下单成功",
          type: "success",
        });
        _this.$router
          .push({
            path: "/customer/order",
          })
          .catch((e) => this.$message.error(e.response.data));
      });
      // 清空状态中的购物车
      _this.$store.dispatch("updateFoodInCart", []);
    },
  },
};
</script>

<style>
.checkout-card {
  width: 600px;
  margin: 0 auto;
}
.checkout-food-title {
  float: left;
  text-align: left;
  margin: 30px;
}
.checkout-food-price {
  float: right;
  margin: 35px 0px;
  width: 100px;
  text-align: left;
}
.checkout-dine-button {
  margin: 20px;
}
.checkout-dineout-button {
  width: 500px;
  height: 80px !important;
  text-align: left !important;
  display: block !important;
  margin: 0px 20px 20px;
}
.checkout-dineout-button:focus,
.checkout-dineout-button:hover {
  color: black !important;
  border-color: #e3a566 !important;
  /* background-color: var(--el-button-hover-bg-color); */
  outline: 0;
  transform: translateY(-2px);
}
.checkout-dineout-button > span {
  display: inline-block !important;
  align-items: left !important;
  width: 100%;
}
.checkout-address {
  font-size: 20px;
}
.checkout-address-icon {
  float: right;
}
.checkout-address-radio {
  /* display: block; */
}
.checkout-address-col {
  margin-bottom: 50px;
}
.checkout-address-add-button {
  border: 2px dashed #e3a566 !important;
}
.checkout-address-add-button:hover {
  color: #e3a566 !important;
  background-color: white !important;
}
.checkout-address-add-button:focus {
  color: rgb(96, 98, 102) !important;
  background-color: white !important;
}
.checkout-return {
  font-family: sanji;
  font-size: 20px !important;
}
.checkout-operation {
  float: right;
  margin-bottom: 30px;
}
.checkout-address-div {
  text-align: left;
}
.checkout-address-delete-btn {
  float: right;
}
.checkout-address-delete-btn:focus {
  background-color: white !important;
}
</style>
